package com.snail.sell.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.snail.sell.Exception.SellException;
import com.snail.sell.Form.OrderForm;
import com.snail.sell.dataobject.OrderDetail;
import com.snail.sell.dto.OrderDTO;
import com.snail.sell.enums.ResultEnums;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 15:04 2017/12/5
 * @Modified By:
 **/
@Slf4j
public class OrderForm2OrderDTOConverter {

    public static OrderDTO converter(OrderForm orderForm){
        OrderDTO orderDTO = new OrderDTO();
        Gson gson = new Gson();

        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetailList = new ArrayList<>();

        try{
            orderDetailList =  gson.fromJson(orderForm.getItems(),new TypeToken<List<OrderDetail>>(){}.getType());
        }
        catch (Exception e){
            log.info("【对象转换】 错误 string={}",orderForm.getItems());
            throw new SellException(ResultEnums.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);


        return orderDTO;
    }
}
